package com.airshare;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class ShareDir {

	File dir;

	String index = "";
	
	public ShareDir(String dirName) {

		dir = new File(dirName);
		
		if (!dir.exists()) {
			System.out.println("Share directory doesn't exist! cannot start file server");
			System.exit(1);
		}
		
		if (!dir.isDirectory()){
			System.out.println("Share directory is not a directoy! cannot start file server");
			System.exit(1);
		}
	}

	private void populateIndex() {
		File[] files = dir.listFiles();
		
		for(int i=0; i<files.length; ++i) {
			if (files[i].canRead()) {
				index += files[i].isDirectory() + files[i].getName() + "\n"; 
			}
		}
	}
	
	public String getIndex() {
		
		if (index == "") {
			populateIndex();
		}
		
		return index;
	}
	
	public long getFileSize(String filename) {
		
		long fileSize = 0L;
		
		File f = new File(dir.getAbsolutePath() + System.getProperty("file.separator") + filename); 
		
		if (f.exists()) {
			fileSize = f.length();
		}
		
		return fileSize;
	}
	
	public boolean fileExists(String filename) {
		String path = dir.getAbsolutePath() + System.getProperty("file.separator") + filename;
		File f = new File(path);
		
		return f.exists();
	}
	
	public void sendFile(DataOutputStream dos, String filename) {
		
		String path = dir.getAbsolutePath() + System.getProperty("file.separator") + filename;
		try {
			DataInputStream fin = new DataInputStream(new FileInputStream(path));
			byte[] buf = new byte[1024];
			int read = 0;
			while ((read = fin.read(buf)) != -1) {
				dos.write(buf);
				dos.flush();
			}
			fin.close();
			dos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void receiveFile(final DataInputStream dis, final String filename, final long fileSize) {
	
//		new Thread() {
//			public void run() {
				ShareDir.this.threadedReceiveFile(dis, filename, fileSize);
//			}
//		}.start();
	}
	
	public void threadedReceiveFile(DataInputStream dis, String filename, long fileSize) {
		
		String path = dir.getAbsolutePath() + System.getProperty("file.separator") + filename;
		try {
			DataOutputStream fout = new DataOutputStream(new FileOutputStream(path));
			long receivedSize = 0;
			
			while (receivedSize < fileSize) {	
				byte[] buf = new byte[1024];
				int read = 0;
				if (fileSize - receivedSize < 1024) {
					read = dis.read(buf, 0, (int)(fileSize - receivedSize));
				}
				else {
					read = dis.read(buf);
				}
				fout.write(buf, 0, read);
				fout.flush();
				receivedSize += read;
			}
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
}
